//
//  XXButton.swift
//  XXSwiftDemo
//
//  Created by admin on 2022/3/28.
//

import UIKit

extension UIButton {

    enum XXBtnImgPosition {
        case left    //图片在左，文字在右
        case right   //图片在右，文字在左
        case top     //图片在上，文字在下
        case bottom  //图片在下，文字在上
    }
    
    var title: String {
        get{
            return titleLabel?.text ?? ""
        }
        set{
            setTitle(newValue, for: .normal)
        }
    }
    var image :UIImage{
        get{
            return (imageView?.image)!
        }
        set{
            setImage(newValue, for: .normal)
        }
    }
    var titleColor : UIColor{
        get{
            return (titleLabel?.textColor)!
        }
        set{
            setTitleColor(newValue, for: .normal)
        }
    }
    var alignment : UIControl.ContentHorizontalAlignment{
        get{
            return contentHorizontalAlignment
        }
        set{
            contentHorizontalAlignment = newValue
        }
    }
    
    // MARK: - 调整图文相对位置
    func imgPostion(postion: XXBtnImgPosition, spacing: CGFloat) {
        let imageWith: CGFloat =  currentImage?.size.width ?? 0
        let imageHeight: CGFloat = currentImage?.size.height ?? 0
        let labelWidth = titleLabel?.intrinsicContentSize.width ?? 0
        let labelHeight = titleLabel?.intrinsicContentSize.height ?? 0
        var imageEdgeInsets: UIEdgeInsets  = UIEdgeInsets.zero;
        var labelEdgeInsets: UIEdgeInsets  = UIEdgeInsets.zero;
        
        switch postion {
        case .top:
            imageEdgeInsets =  UIEdgeInsets(top: -labelHeight - spacing/2.0, left: 0, bottom: 0, right:  -labelWidth)
            labelEdgeInsets = UIEdgeInsets(top: 0, left: -imageWith, bottom: -imageHeight - spacing/2.0, right: 0)
        case .left:
            imageEdgeInsets = UIEdgeInsets(top: 0, left: -spacing/2.0, bottom: 0, right: spacing/2.0);
            labelEdgeInsets = UIEdgeInsets(top: 0,left: spacing/2.0, bottom: 0, right: -spacing/2.0);
        case .bottom:
            imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: -labelHeight - spacing/2.0, right: -labelWidth);
            labelEdgeInsets = UIEdgeInsets(top: -imageHeight - spacing/2.0,left: -imageWith, bottom: 0, right: 0);
        case .right:
            imageEdgeInsets = UIEdgeInsets(top: 0,left: labelWidth + spacing/2.0, bottom: 0, right: -labelWidth-spacing/2.0);
            labelEdgeInsets = UIEdgeInsets(top: 0, left: -imageWith - spacing/2.0, bottom: 0, right: imageWith+spacing/2.0);
        }
        titleEdgeInsets = labelEdgeInsets;
        self.imageEdgeInsets = imageEdgeInsets;
    }
}

class XXButton: UIButton {
//    typealias XXVoidBlock = ()->Void
//    typealias XXButtonVoidBlock = ()->XXButton
    
    private var click:XXVoidBlock?{
        didSet{
            addTarget(self, action: #selector(btnAction), for: .touchUpInside)
        }
    }
    var clickTimeInterval = 0.5
    var touchAreaInsets:UIEdgeInsets  = edgeInsets(0, 0, 0, 0) // 热区
    // MARK: - action
    @objc func btnAction() {
        guard self.isUserInteractionEnabled else{
            return
        }
        guard let block = click else{
            return
        }
        block()
        if countDown>0{
            if isAuto{
                beginCountDown()
            }
        }else{
            if clickTimeInterval > 0{
                self.isUserInteractionEnabled = false
                DispatchQueue.main.asyncAfter(deadline: .now() + clickTimeInterval) {
                    self.isUserInteractionEnabled = true
                }
            }
        }
    }
    
    @discardableResult
    func click(_ block:@escaping XXVoidBlock) -> XXButton{
        click = block
        return self
    }
//    func done(){ }
    // MARK: - 按钮热区
    override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
        var bounds = self.bounds
        bounds = CGRect.init(x: bounds.origin.x - self.touchAreaInsets.left, y: bounds.origin.y - self.touchAreaInsets.top, width: bounds.size.width + self.touchAreaInsets.left + self.touchAreaInsets.right, height: bounds.size.height + self.touchAreaInsets.top + self.touchAreaInsets.bottom)
        return bounds.contains(point)
    }
    
    // MARK: 倒计时
    private var countDown = 0
    private var countDownNum = 0
    private var oldTitle: String = ""
    private var isAuto = true
    private var leftStr:String = ""
    private var rightStr:String = ""
    private var timer:Timer?
    private var countDownBlock:XXIntBlock?
    private var countDownEndBlock:XXVoidBlock?
    
    @discardableResult
    func countDownBlock(_ block:@escaping XXIntBlock) -> XXButton{
        countDownBlock = block
        return self
    }
    
    @discardableResult
    func countDownEndBlock(_ block:@escaping XXVoidBlock) -> XXButton{
        countDownEndBlock = block
        return self
    }
    
    @discardableResult
    func setCountDown(_ left:String, _ num:Int, right:String, _ auto:Bool = true) ->XXButton {
        countDown = num
        countDownNum = num
        leftStr = left
        rightStr = right
        oldTitle = self.title
        return self
    }
    
    func beginCountDown(){
        self.isUserInteractionEnabled = false
        timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] timer in
            if self?.countDownNum ?? 0 > 0{
                self?.countDownNum -= 1
                self?.setCountDownTitle(num: self?.countDownNum ?? 0)
                if let b = self?.countDownBlock{
                    b(self?.countDownNum ?? 0)
                }
            }else{
                timer.invalidate()
                self?.countDownNum = self?.countDown ?? 0
                self?.title = self?.oldTitle ?? ""
                if let b = self?.countDownEndBlock{
                    b()
                }
                self?.isUserInteractionEnabled = true
            }
        }
    }
    
    func endCountDown(){
        if let t = timer{
            t.invalidate()
        }
        if let b = self.countDownEndBlock{
            b()
        }
        self.countDownNum = self.countDown
        self.title = self.oldTitle
    }
    
    private func setCountDownTitle(num:Int){
        self.title = "\(leftStr)\(num)\(rightStr)"
    }
}

extension XXButton {

    convenience init(title:String ,color:UIColor = .black ,font:UIFont = .system(15) ,frame: CGRect = .zero) {
        self.init(frame:frame)
        setTitle(title, for: .normal)
        setTitleColor(color, for: .normal)
        titleLabel?.font = font
    }
    
    convenience init(imgName:String ,frame: CGRect = .zero) {
        self.init(frame:frame)
        setImage(kImage(imgName), for:.normal)
    }
    
    convenience init(title:String, imgName:String, color:UIColor = .black ,font:UIFont = .system(15), frame: CGRect = .zero ) {
        self.init(frame:frame)
        setTitle(title, for: .normal)
        setTitleColor(color, for: .normal)
        titleLabel?.font = font
        setImage(kImage(imgName), for: .normal)
    }
}

